<?php

namespace app\home\controller;

use think\facade\View;
use think\facade\Lang;
use think\facade\Db;
use GatewayClient\Gateway;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamStateRequest;
use \Firebase\JWT\JWT;
use AlibabaCloud\Client\AlibabaCloud;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class MemberLive extends BaseMember {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/live.lang.php');
    }

    /**
     * 直播间
     *
     * @param
     * @return
     */
    public function index() {
        $live_apply_id = input('param.live_apply_id');
        if (!$live_apply_id) {
            $this->error(lang('param_error'));
        }

        //获取最近未结束的直播
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_id', '=', $live_apply_id);
        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (!$live_apply) {
            $this->error(lang('live_not_exit'));
        }



        if ($live_apply['live_apply_play_time'] > TIMESTAMP) {
            $this->error(lang('live_not_begin'));
        }
        $extral_info = array();
        $live_apply['live_apply_cover_image_url'] = ds_get_pic(ATTACH_COMMON,config('ds_config.default_goods_image'));
        if ($live_apply['live_apply_cover_video']) {
            $live_apply['live_apply_cover_video_url'] = ds_get_pic( ATTACH_LIVE_APPLY . '/' . $live_apply['live_apply_user_id'] , $live_apply['live_apply_cover_video']);
        } elseif ($live_apply['live_apply_cover_image']) {
            $live_apply['live_apply_cover_image_url'] = ds_get_pic( ATTACH_LIVE_APPLY . '/' . $live_apply['live_apply_user_id'] , $live_apply['live_apply_cover_image']);
        }
        switch ($live_apply['live_apply_user_type']) {
            case 2:
                $store_model = model('store');
                $store_info = $store_model->getOneStore(array(array('store_id', '=', $live_apply['live_apply_user_id'])), 'store_id,store_collect,store_name,store_avatar,area_info');
                if (!$store_info) {
                    $this->error(lang('ds_store_is_not_exist'));
                }
                $live_apply['live_apply_user_avatar'] = get_store_logo($store_info['store_avatar']);
                $live_apply['live_apply_user_name'] = $store_info['store_name'];
                $live_apply['live_apply_fans'] = $store_info['store_collect'];
                $live_apply['area_info'] = $store_info['area_info'];
                $favorites_model = model('favorites');
                $c = (int) $favorites_model->getStoreFavoritesCountByStoreId($store_info['store_id'], $this->member_info['member_id']);
                $live_apply['is_favorate'] = $c > 0;
                break;
        }
        $online_info = false;
        if (config('ds_config.instant_message_register_url')) {
            // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
            try {
                Gateway::$registerAddress = config('ds_config.instant_message_register_url');
                $online_info = array(
                    'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                    'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id),
                );
            } catch (\Exception $e) {
                $msg = $e->getMessage();
            }
        }
        $goods_commonid = Db::name('live_apply_goods')->where('live_apply_id', $live_apply_id)->column('goods_commonid');
        $goods_model = model('goods');
        if (!empty($goods_commonid)) {
            $goods_list = $goods_model->getGoodsUnionList(array(array('goodscommon.goods_commonid', 'in', $goods_commonid)), 'goods_id,goods_storage,goodscommon.goods_commonid,goodscommon.goods_price,goodscommon.goods_name,goodscommon.goods_image', '', 'goodscommon.goods_commonid');
            foreach ($goods_list as $k => $v) {
                if(!$v['goods_storage']){
                        $goods_info=$goods_model->getGoodsStorageByCommonId($v['goods_commonid']);
                        if($goods_info){
                            $goods_list[$k]['goods_id']=$goods_info['goods_id'];
                        }
                    }
                $goods_list[$k]['goods_image'] = goods_cthumb($v['goods_image']);
            }
            $live_apply['goods_list'] = $goods_list;
        }
        //通过链接获取腾讯fileId
        $live_apply['file_id'] = '';
        $live_apply['video_type'] = '';
        if ($live_apply['live_apply_video']) {
            $preg_str = '/\/\S{8}vodcq' . config('ds_config.vod_tencent_appid') . '\/\S{8}(\d{19})\//';
            if (preg_match($preg_str, $live_apply['live_apply_video'], $matches)) {
                if (config('ds_config.vod_tencent_appid') && config('ds_config.vod_tencent_play_key')) {
                    $appId = config('ds_config.vod_tencent_appid'); // 用户 appid
                    $fileId = $matches[1]; // 目标 FileId
                    $currentTime = TIMESTAMP;
                    $psignExpire = $currentTime + 3600; // 可任意设置过期时间，示例1h
                    $urlTimeExpire = dechex($psignExpire); // 可任意设置过期时间，16进制字符串形式，示例1h
                    $key = config('ds_config.vod_tencent_play_key');

                    $payload = array(
                        "appId" => $appId,
                        "fileId" => $fileId,
                        "currentTimeStamp" => $currentTime,
                        "expireTimeStamp" => $psignExpire,
                        "urlAccessInfo" => array(
                            "t" => $urlTimeExpire
                        )
                    );

                    $jwt = JWT::encode($payload, $key, 'HS256');
                    $live_apply['video_type'] = 'tencent';
                    $live_apply['file_id'] = $fileId;
                    $live_apply['psign'] = $jwt;
                }
            } else if (preg_match('/aliyuncs/', $live_apply['live_apply_video'], $matches)) {
                $live_apply['video_type'] = 'aliyun';
            }
        }
        
        View::assign('online_info', $online_info);

        View::assign('member_avatar', get_member_avatar_for_id($this->member_info['member_id']));
        View::assign('member_points', $this->member_info['member_points']);
        $active = false;
        if ($live_apply['live_apply_end_time'] > TIMESTAMP) {

            //判断当前流状态
            if (config('ds_config.video_type') == 'aliyun') {
                $live_apply['video_type'] = 'aliyun';
                if (!config('ds_config.aliyun_live_push_domain')) {
                    $this->error(lang('aliyun_live_push_domain_empty'));
                }
                if (!config('ds_config.aliyun_live_push_key')) {
                    $this->error(lang('aliyun_live_push_key_empty'));
                }
                if (!config('ds_config.aliyun_live_play_domain')) {
                    $this->error(lang('aliyun_live_play_domain_empty'));
                }
                if (!config('ds_config.aliyun_live_play_key')) {
                    $this->error(lang('aliyun_live_play_key_empty'));
                }
                $regionId = 'cn-shanghai';
                AlibabaCloud::accessKeyClient(config('ds_config.aliyun_access_key_id'), config('ds_config.aliyun_access_key_secret'))
                        ->regionId($regionId)
                        ->asDefaultClient();

                try {
                    $result = AlibabaCloud::rpc()
                            ->product('live')
                            // ->scheme('https') // https | http
                            ->version('2016-11-01')
                            ->action('DescribeLiveStreamsOnlineList')
                            ->method('POST')
                            ->host('live.aliyuncs.com')
                            ->options([
                                'query' => [
                                    'RegionId' => $regionId,
                                    'DomainName' => config('ds_config.aliyun_live_push_domain'),
                                    'AppName' => "live",
                                    'StreamName' => 'live_apply_' . $live_apply['live_apply_id'],
                                    'PageSize' => "1",
                                    'PageNum' => "1",
                                    'QueryType' => "strict",
                                ],
                            ])
                            ->request();
                    if ($result->TotalNum) {
                        $active = true;
                    }
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            } else {
                $live_apply['video_type'] = 'tencent';
                if (!config('ds_config.live_push_domain')) {
                    $this->error(lang('live_push_domain_empty'));
                }
                if (!config('ds_config.live_push_key')) {
                    $this->error(lang('live_push_key_empty'));
                }
                if (!config('ds_config.live_play_domain')) {
                    $this->error(lang('live_play_domain_empty'));
                }

                try {

                    $cred = new Credential(config('ds_config.vod_tencent_secret_id'), config('ds_config.vod_tencent_secret_key'));
                    $httpProfile = new HttpProfile();
                    $httpProfile->setEndpoint("live.tencentcloudapi.com");

                    $clientProfile = new ClientProfile();
                    $clientProfile->setHttpProfile($httpProfile);
                    $client = new LiveClient($cred, "", $clientProfile);

                    $req = new DescribeLiveStreamStateRequest();

                    $params = '{"AppName":"live","DomainName":"' . config('ds_config.live_push_domain') . '","StreamName":"' . 'live_apply_' . $live_apply['live_apply_id'] . '"}';
                    $req->fromJsonString($params);


                    $resp = $client->DescribeLiveStreamState($req);
                } catch (TencentCloudSDKException $e) {
                    $this->error($e->getMessage());
                }
                if ($resp->StreamState == 'active') {
                    $active = true;
                }
            }
            //生成推流url
            $live_apply['live_apply_push_url'] = $live_apply_model->getPushUrl('live_apply_' . $live_apply['live_apply_id'], $live_apply['live_apply_end_time']);
            //生成拉流url
            $live_apply['live_apply_play_url'] = $live_apply_model->getPlayUrl('live_apply_' . $live_apply['live_apply_id'], $live_apply['live_apply_end_time']);
        }
        View::assign('live_apply_info', array_merge($live_apply, $extral_info, array('instant_message_url' => config('ds_config.instant_message_gateway_url'))));
        View::assign('active', $active);
        return View::fetch($this->template_dir . 'index');
    }

    function join_live() {
        session('name');
        $live_apply_id = input('param.live_apply_id');
        $client_id = input('param.client_id');
        if (!config('ds_config.instant_message_register_url')) {
            ds_json_encode(10001, lang('instant_message_register_url_empty'));
        }
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }

        // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
        try {
            Gateway::$registerAddress = config('ds_config.instant_message_register_url');
            // client_id与uid绑定
            Gateway::bindUid($client_id, '0:' . $this->member_info['member_id']);
            $online_item = array(
                'instant_message_from_avatar' => get_member_avatar_for_id($this->member_info['member_id']),
                'instant_message_from_id' => $this->member_info['member_id'],
                'instant_message_from_type' => 0,
                'instant_message_from_name' => $this->member_info['member_name']
            );
            Gateway::setSession($client_id, $online_item);
            // 加入某个群组（可调用多次加入多个群组）
            Gateway::joinGroup($client_id, 'live_apply_' . $live_apply_id);
            //更新在线人数
            Gateway::sendToGroup('live_apply_' . $live_apply_id, json_encode(array(
                'type' => 'join',
                'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id)
            )));
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
        Db::name('live_apply')->where('live_apply_id', $live_apply_id)->inc('live_apply_view_count')->update();
        ds_json_encode(10000, '');
    }

    function add_like() {
        $live_apply_id = input('param.live_apply_id');

        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }
        Db::name('live_apply')->where('live_apply_id', $live_apply_id)->inc('live_apply_like_count')->update();
        ds_json_encode(10000, '');
    }

    function add_gift() {
        $live_apply_id = input('param.live_apply_id');
        $num = intval(input('param.num'));
        if (!config('ds_config.instant_message_register_url')) {
            ds_json_encode(10001, lang('instant_message_register_url_empty'));
        }
        if ($num < 1) {
            ds_json_encode(10001, lang('num_error'));
        }
        $live_apply_model = model('live_apply');
        $condition = array();
        $condition[] = array('live_apply_state', '=', 1);
        $condition[] = array('live_apply_end_time', '>', TIMESTAMP);
        $condition[] = array('live_apply_id', '=', $live_apply_id);

        $live_apply = $live_apply_model->getLiveApplyInfo($condition);
        if (empty($live_apply)) {
            ds_json_encode(10001, lang('live_not_exit'));
        }
        if ($this->member_info['member_points'] < 100) {
            ds_json_encode(10001, lang('points_not_enough'));
        }
        $points_model = model('points');
        Db::startTrans();
        try {
            switch ($live_apply['live_apply_user_type']) {
                case 2:
                    $store_model = model('store');
                    $store_info = $store_model->getOneStore(array(array('store_id', '=', $live_apply['live_apply_user_id'])), 'member_id,member_name');
                    if (!$store_info) {
                        throw new \think\Exception(lang('ds_store_is_not_exist'), 10006);
                    }
                    $points_model->savePointslog('gift', array(
                        'pl_memberid' => $store_info['member_id'], 'pl_membername' => $store_info['member_name'], 'pl_desc' => $live_apply['live_apply_name'] . lang('live_present_rocket'), 'pl_points' => 100 * $num
                    ));
                    $points_model->savePointslog('gift', array(
                        'pl_memberid' => $this->member_info['member_id'], 'pl_membername' => $this->member_info['member_name'], 'pl_desc' => $live_apply['live_apply_name'] . lang('live_present_rocket'), 'pl_points' => -100 * $num
                    ));
                    break;
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            ds_json_encode(10001, $e->getMessage());
        }

        // 设置GatewayWorker服务的Register服务ip和端口，请根据实际情况改成实际值(ip不能是0.0.0.0)
        try {
            Gateway::$registerAddress = config('ds_config.instant_message_register_url');

            Gateway::sendToGroup('live_apply_' . $live_apply_id, json_encode(array(
                'type' => 'gift',
                'gift_num' => $num,
                'member' => array(
                    'member_id' => $this->member_info['member_id'],
                    'member_name' => $this->member_info['member_name'],
                    'member_avatar' => get_member_avatar_for_id($this->member_info['member_id'])
                ),
                'online_count' => Gateway::getClientIdCountByGroup('live_apply_' . $live_apply_id),
                'online_list' => Gateway::getClientSessionsByGroup('live_apply_' . $live_apply_id)
            )));
        } catch (\Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
        ds_json_encode(10000, '', array('member_points' => $this->member_info['member_points'] - 100 * $num));
    }

}
